package com.wsx.sky.gateway.inner;

import com.wsx.sky.gateway.bean.GateData;
import com.wsx.sky.gateway.bean.GateParam;
import com.wsx.sky.gateway.inner.model.Dept;
import com.wsx.sky.gateway.inner.service.DeptService;
import com.wsx.sky.redis.RedisService;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author wangshuaixin
 * @Title: com.wsx.sky.gateway.inner.InnerController
 * @Description: 内部单容器服务的业务操纵
 * @date 2018/12/07
 */
@RestController
@RequestMapping("/inner")
public class InnerController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private RedisService redisService;


    @RequestMapping(
            value = "/get/{card}",
            method = {RequestMethod.GET}
    )
    public GateData inner(@PathVariable("card") int card) {
        Dept dept = null;
        String value = redisService.getString(String.valueOf(card));
        if (null == value) {
            dept = deptService.find(card);
            if (null == dept) {
                return new GateData(40004);
            }
            redisService.setObject(String.valueOf(card), dept);
        }
        if (null != dept) {
            return new GateData().buildDatas(dept);
        }
        return new GateData(40004);
    }

    @RequestMapping(
            value = "/find/{card}",
            method = {RequestMethod.GET}
    )
    public GateData find(@PathVariable("card") int card) {
        String tracid = TraceContext.traceId();
        System.out.println(tracid);
        Dept dept = redisService.getObject(String.valueOf(card), Dept.class);
        if (null != dept) {
            return new GateData().buildDatas(dept);
        }

        dept = deptService.find(card);
        if (null == dept) {
            return new GateData(40004);
        }
        redisService.setObject(String.valueOf(card), dept);

        if (null != dept) {
            return new GateData().buildDatas(dept);
        }
        return new GateData(40004);
    }


    @RequestMapping(
            value = "/save",
            method = {RequestMethod.POST}
    )
    public GateData save(@RequestBody GateParam gateParam) {
        if (null == gateParam
                || StringUtils.isEmpty(gateParam.getName())) {
            return new GateData(30001);
        }
        int num = deptService.save(gateParam.getName());
        if (num == 1) {
            return new GateData();
        }
        return new GateData(50001);
    }
}
